package club.babyf.nativeai.config;

import club.babyf.nativeai.utils.IpUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * WebConfig.
 *
 * @author zhanglei.
 * @date 2023/1/30 18:38.
 * @description Web配置.
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {

    /**
     * 添加拦截器
     *
     * @param registry 拦截器注册
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new HandlerInterceptor() {

                    @Override
                    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
                        // 获取请求参数
                        // 获取请求IP地址
                        String ipAddr = IpUtil.getIpAddr(request);
                        // 获取请求URI
                        String requestUri = request.getRequestURI();
                        log.info("request = url: {}, ipAddr: {}", requestUri, ipAddr);
                        // 鉴权暂时不做特殊处理，只进行简单格式校验
                        // 获取授权令牌
                        String authorization = request.getHeader("Authorization");
                        // 判断授权令牌是否为空
                        if (StrUtil.isBlank(authorization)) {
                            log.error("request = url: {}, Authorization is blank", request.getRequestURI());
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            return false;
                        }
                        // 判断授权令牌格式是否正确
                        String[] authorizationArr = authorization.split(" ");
                        if (authorizationArr.length != 2) {
                            log.error("request = url: {}, Authorization format error", request.getRequestURI());
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            return false;
                        }
                        // 判断授权令牌是否以Bearer开头
                        String bearer = authorizationArr[0];
                        if (!StrUtil.equals(bearer, "Bearer")) {
                            log.error("request = url: {}, Authorization should start with Bearer", request.getRequestURI());
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            return false;
                        }
                        return true;
                    }

                })
                .addPathPatterns("/**")
                .excludePathPatterns("/wechat");
    }

}
